package com.action;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pojo.Dep;
import com.service.DepService;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@CrossOrigin("*")
@RequestMapping("/api")
public class DepAction {

    @Autowired
    private DepService depService;

    @Value("${upload.tmp.dir}")
    private  String tmp; //临时

    @Value("${upload.dir}")
    private  String images;//正式

    @RequestMapping("/saveOrUpdateDep")
    public ResponseBean  saveOrUpdateDep(Dep dep)
    {
        boolean result = depService.saveOrUpdate(dep);

        if (result) {
            //复制到正式环境images
           // String images = request.getServletContext().getRealPath("/images");
            File file = new File(images);
            if (file.exists() == false) {
                file.mkdirs();
            }
            FileUtil.copy(tmp + "/" + dep.getImage(), images + "/" + dep.getImage(), true);
            return new ResponseBean(200, 0, "新增成功");
        }

        return new ResponseBean(500,0,null);
    }

    @RequestMapping("/searchDep")
    public ResponseBean searchDep(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int limit, Integer depId, String depName)
    {
        IPage result = depService.searchDep(page,limit,depId,depName);
        return new ResponseBean(0,result.getTotal(),result.getRecords());
    }


    @RequestMapping("/removeDepById")
    public ResponseBean  removeDepById(String depId)
    {
        boolean f = depService.removeById(depId);
        int code = f ? 200:500;
        return new ResponseBean(code,0,null);
    }


}
